package com.mc.service.did.impl;

import java.util.concurrent.TimeUnit;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mc.pojo.po.LeafIdPO;


@Service
public class IdDbLoader{

	@Autowired
	private DbData dbData;

	@Autowired
	private RedissonClient redissonClient;

	public LeafIdPO handleDb(String bizTag) {
        // The prefix identifier of the key in Redis, default did: 
		RLock rLock = redissonClient.getLock("did:" + bizTag);
		rLock.lock(8, TimeUnit.SECONDS);

		LeafIdPO po = dbData.getDb(bizTag);
		try {

			// current
			Long maxId = po.getMaxId();
			Integer step = po.getStep();

			// update
			Integer result = dbData.updateDb(maxId + step, bizTag, po.getVersion());
			if (1 == result) {
				po.setMaxId(maxId + step);
			} else {
				return null;
			}

		} finally {
			rLock.unlock();
		}
		
		po.setVersion(po.getVersion() + 1);
		return po;
	}



}
